#pragma once

#include "Camera.h"

class VirtualCamera : public Camera
{
private:
    set<string> picture_type = {"jpg", "png"};
    bool is_pitcure;//ture表示要打开图片
    VideoCapture cam;

public:
    VirtualCamera(string cam); 
    ~VirtualCamera(); 
    int open();

    int close();
    Mat getFrame();
};


/**
 * @author: 王占坤
 * @description: 创建一个打开视频的虚拟相机
 * @param: string video_path 需要打开的视频路径
 * @return: 
 * @throw: 
 */
VirtualCamera::VirtualCamera(string video_path) : Camera(video_path)
{
    int idx = video_path.find_last_of('.');
    string end_with = video_path.substr(idx + 1);
#ifdef PRINT_INFO
    cout << "VirtualCamera::VirtualCamera cam_name = " << this->cam_name << endl;
    cout << "VirtualCamera::VirtualCamera end_with = " << end_with << endl;
#endif
    if(this->picture_type.find(end_with) != this->picture_type.end())
            this->is_pitcure = true;
    else
    {
        this->is_pitcure = false;
    }
    idx = this->cam_name.find_last_of("/");
    this->device_id = this->cam_name.substr(idx + 1);
}

VirtualCamera::~VirtualCamera()
{
}

inline
int VirtualCamera::open()
{
    if(!is_pitcure)
    {
        try
        {
            cam.open(cam_name);
        }
        catch(const std::exception& e)
        {
            std::cerr << e.what() << '\n';
        }
        
        this->is_opened = cam.isOpened();
    }
    return (this->is_opened ? 0 : -1);
}

inline
int VirtualCamera::close()
{
    is_opened = false;
    this->cam.release();
}


inline
Mat VirtualCamera::getFrame()
{
    Mat frame;
    if(!is_pitcure)
    {
        bool status = cam.read(frame); 
        if (!status) {
            cout << "Video ended. " << endl; 
            // exit(0); 
            raise(SIGINT);
        }
    }
    else{
        frame = imread(this->cam_name);
        this->is_opened = false;
        if(frame.empty())
        {
            cout << "cannot open picture: " << this->cam_name << endl;
            // pthread_exit(0);
            raise(SIGINT);
        }
    }
    // resize(frame, frame, Size(frame_width, frame_height));  
    return frame;
}
